/*
 *所有关于equipmentstatuslogs类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*equipmentstatuslogsService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VolPro.Core.BaseProvider;
using VolPro.Core.Extensions.AutofacManager;
using VolPro.Entity.DomainModels;
using System.Linq;
using VolPro.Core.Utilities;
using System.Linq.Expressions;
using VolPro.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using SMes.DbMethod.IRepositories;
using SMes.DbMethod.ViewModel;
using System.Collections.Generic;
using System.ComponentModel;

namespace SMes.DbMethod.Services
{
    public partial class equipmentstatuslogsService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IequipmentstatuslogsRepository _repository;//访问数据库
        private readonly IequipmentRepository _equipmentRepository;

        [ActivatorUtilitiesConstructor]
        public equipmentstatuslogsService(
            IequipmentstatuslogsRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IequipmentRepository equipmentRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _equipmentRepository = equipmentRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public  async Task <WebResponseContent> AddEqStatuslogs(List<DetailData> datas)
        {
            var webResponse = new WebResponseContent();
            var toAdd = new List<equipmentstatuslogs>();
            var toUpdate=new List<equipmentstatuslogs>();
            foreach (var data in datas)
            {
                var eq = await _equipmentRepository.FindAsyncFirst(x => x.SerialNo == data.EquipmentCode);
                if (eq == null) return webResponse.Error($"数据库中查询不到{data.EquipmentCode}的设备编码");
                var eqStatuslog =  await _repository.FindAsyncFirst(x => x.EquipmentID == eq.EquipmentID);
                var keyValue = GetStatusValue(data.Tag);
                if (eqStatuslog == null)
                {
                    
                    var newEqStatusLog = new equipmentstatuslogs()
                    {
                        StatusID = Guid.NewGuid().ToString(),
                        EquipmentID = eq.EquipmentID,
                        StatusType = keyValue.Key,
                        StatusValue = keyValue.Value,
                        StartTime = DateTime.Now,
                        EndTime = DateTime.Now
                    };
                    toAdd.Add(newEqStatusLog);
                }
                else
                {
                    eqStatuslog.StatusType=keyValue.Key;
                    eqStatuslog.StatusValue=keyValue.Value;
                    eqStatuslog.EndTime=DateTime.Now;
                    toUpdate.Add(eqStatuslog);
                }
            }
             _repository.AddRange(toAdd);
            _repository.UpdateRange(toUpdate);
            await _repository.SaveChangesAsync();
#if false
            if (datas == null || datas.Count() == 0) { return webResponse.Error("无故障数据"); }
            var datasFilter = datas.Select(s => new { s.EquipmentCode, s.Value }).ToList();
            var dataEqCodes = datasFilter.Select(x => x.EquipmentCode);
            var dataTags = datasFilter.Select(x => x.Value);
            //var eqFliters = await _equipmentRepository.FindAsync(x => dataEqCodes.Contains(x.SerialNo), x => new
            //{
            //    x.EquipmentID,
            //    x.SerialNo
            //});
            var eqFliters = await _equipmentRepository.FindAsIQueryable(x => dataEqCodes.Contains(x.SerialNo)).Select(x => new { x.EquipmentID, x.SerialNo })
                .AsNoTracking().ToListAsync();
            if (eqFliters == null || eqFliters.Count == 0) { return webResponse.Error("数据库中查询不到设备编码"); }
            //var eqFlitersCodes = eqFliters.Select(x => x.SerialNo);
            var eqFlitersIDs = eqFliters.Select(x => x.EquipmentID).ToList();
            var CheckData = dataEqCodes.Except(eqFliters.Select(x => x.SerialNo)).ToList();
            if (CheckData != null && CheckData.Count > 0)
            {
                return webResponse.Error($"设备编码{string.Join(";", CheckData)}数据库中不存在");
            }
            var toUpdate = eqFliters.Join(datasFilter, u => u.SerialNo, t => t.EquipmentCode,
                    (u, t) => new products
                    {

                    }).ToList();
#endif
            webResponse.OK("设备状态变化添加成功");
            webResponse.Code = "200;";
            return webResponse;
        }
        private KeyValuePair<string,string> GetStatusValue(int status)
        {
            //var statusInt = Convert.ToInt32(status);
            //string value = string.Empty;
            switch (status)
            {
                case 0:
                    return new KeyValuePair<string,string>(StatusType.shutdown.ToString(), "未运行");
                case 1:
                    return new KeyValuePair<string, string>(StatusType.running.ToString(), "运行中");
                case 2:                 
                    return new KeyValuePair<string, string>(StatusType.normal.ToString(), "正常");
                case 3:                  
                    return new KeyValuePair<string, string>(StatusType.error.ToString(), "异常");
                //case 4:                  
                //    return new KeyValuePair<string, string>(StatusType.idle.ToString(), "待机");
                default:
                    return new KeyValuePair<string, string>(StatusType.error.ToString(), "异常");  
            }
            //return value;
        }
        public enum StatusType
        {
            [Description("未运行")]
            shutdown = 0,
            [Description("运行中")]
            running = 1,
            [Description("正常")]
            normal = 2,
            [Description("异常")]
            error = 3,
            //[Description("待机")]
            //idle = 4
        }
    }
}
